package com.wrx.swing.panel.mndata;

import com.wrx.dto.mndata.mnrawdata.MnRawDataResp;
import com.wrx.dto.mndata.mnrawdata.MnRawDataVO;
import com.wrx.service.mndata.MnDataService;
import com.wrx.swing.form.MnRawDataFormFields;
import com.wrx.util.SwingComponentUtil;

import javax.swing.*;
import java.awt.*;

/**
 * 模拟采集数据面板
 */
public class MnRawDataPanel {

    private static final int LABEL_WIDTH = 200;

    private final MnDataService mnDataService;
    private final JFrame parentFrame;

    public MnRawDataPanel(MnDataService mnDataService, JFrame parentFrame) {
        this.mnDataService = mnDataService;
        this.parentFrame = parentFrame;
    }

    public JPanel createPanel() {
        JPanel panel = new JPanel(new BorderLayout());

        // 创建表单字段管理对象
        MnRawDataFormFields formFields = new MnRawDataFormFields();

        // 创建输入面板（包含按钮）
        JPanel inputPanel = createInputPanel(formFields);

        // 创建日志区域
//        JScrollPane scrollPane = SwingComponentUtil.createLogArea(formFields.logArea);
//        scrollPane.setPreferredSize(new Dimension(0, 200));

        // 组装面板
        panel.add(inputPanel, BorderLayout.CENTER);
//        panel.add(scrollPane, BorderLayout.SOUTH);

        return panel;
    }

    /**
     * 创建SQL生成输入面板
     */
    private JPanel createInputPanel(MnRawDataFormFields fields) {
        JPanel inputPanel = new JPanel();
        inputPanel.setLayout(new BoxLayout(inputPanel, BoxLayout.Y_AXIS));
        inputPanel.setBorder(BorderFactory.createTitledBorder("参数输入"));

        JPanel basicInfoPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 16, 8));
        basicInfoPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
        basicInfoPanel.add(createInlineFormItem("开始时间:", fields.collectTimeStartField));
        basicInfoPanel.add(createInlineFormItem("结束时间:", fields.collectTimeEndField));
        inputPanel.add(basicInfoPanel);

        // 默认参数开关
        JCheckBox defaultParamsCheckBox = fields.defaultParamsCheckBox;
        inputPanel.add(createFormRow("默认参数:", defaultParamsCheckBox));

        // 默认参数字段（租户ID、租户名称、表名和数据库名，根据复选框显示/隐藏）
        JPanel defaultParamsPanel = new JPanel();
        defaultParamsPanel.setLayout(new BoxLayout(defaultParamsPanel, BoxLayout.Y_AXIS));
        defaultParamsPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
        defaultParamsPanel.setBorder(BorderFactory.createEmptyBorder(0, 20, 0, 0));
        
        // 第一行：租户ID、租户名称
        JPanel defaultParamsRow1 = new JPanel(new FlowLayout(FlowLayout.LEFT, 16, 8));
        defaultParamsRow1.setAlignmentX(Component.LEFT_ALIGNMENT);
        defaultParamsRow1.add(createInlineFormItem("租户ID:", fields.tenantIdField));
        defaultParamsRow1.add(createInlineFormItem("租户名称:", fields.tenantNameField));
        
        // 第二行：表名、数据库名
        JPanel defaultParamsRow2 = new JPanel(new FlowLayout(FlowLayout.LEFT, 16, 8));
        defaultParamsRow2.setAlignmentX(Component.LEFT_ALIGNMENT);
        defaultParamsRow2.add(createInlineFormItem("表名:", fields.tableNameField));
        defaultParamsRow2.add(createInlineFormItem("数据库名:", fields.dataBaseNameField));
        
        // 第三行：开始id
        JPanel defaultParamsRow3 = new JPanel(new FlowLayout(FlowLayout.LEFT, 16, 8));
        defaultParamsRow3.setAlignmentX(Component.LEFT_ALIGNMENT);
        defaultParamsRow3.add(createInlineFormItem("开始id(不指定则使用自增):", fields.startIdField));
        
        defaultParamsPanel.add(defaultParamsRow1);
        defaultParamsPanel.add(defaultParamsRow2);
        defaultParamsPanel.add(defaultParamsRow3);
        defaultParamsPanel.setVisible(defaultParamsCheckBox.isSelected());
        inputPanel.add(defaultParamsPanel);

        defaultParamsCheckBox.addActionListener(e -> {
            boolean selected = defaultParamsCheckBox.isSelected();
            defaultParamsPanel.setVisible(selected);
            inputPanel.revalidate();
            inputPanel.repaint();
        });

        // 模拟类型选择（单选框）
        JPanel simulateTypePanel = new JPanel();
        simulateTypePanel.setLayout(new BoxLayout(simulateTypePanel, BoxLayout.X_AXIS));
        simulateTypePanel.setAlignmentX(Component.LEFT_ALIGNMENT);
        simulateTypePanel.add(fields.generateJsonRadio);
        simulateTypePanel.add(Box.createHorizontalStrut(20));
        simulateTypePanel.add(fields.generateSqlRadio);
        simulateTypePanel.add(Box.createHorizontalStrut(20));
        simulateTypePanel.add(fields.insertDbRadio);
        inputPanel.add(createFormRow("模拟类型:", simulateTypePanel));

        // 数据库连接字段（仅在插入数据库模式时显示）
        JPanel autoFieldsPanel = new JPanel();
        autoFieldsPanel.setLayout(new BoxLayout(autoFieldsPanel, BoxLayout.Y_AXIS));
        autoFieldsPanel.setBorder(BorderFactory.createEmptyBorder(0, 20, 0, 0));
        autoFieldsPanel.add(createFormRow("用户名:", fields.userNameField));
        autoFieldsPanel.add(createFormRow("密码:", fields.passwordField));
        autoFieldsPanel.add(createFormRow("数据库地址:", fields.databaseUrlField));
        autoFieldsPanel.setVisible(fields.insertDbRadio.isSelected());
        autoFieldsPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
        inputPanel.add(autoFieldsPanel);

        // 单选框事件监听
        fields.generateSqlRadio.addActionListener(e -> {
            autoFieldsPanel.setVisible(false);
            inputPanel.revalidate();
            inputPanel.repaint();
        });
        fields.insertDbRadio.addActionListener(e -> {
            autoFieldsPanel.setVisible(true);
            inputPanel.revalidate();
            inputPanel.repaint();
        });
        fields.generateJsonRadio.addActionListener(e -> {
            autoFieldsPanel.setVisible(false);
            inputPanel.revalidate();
            inputPanel.repaint();
        });
        // 添加点位面板
        inputPanel.add(createPointCodeNamePanel(fields));

        // 生成按钮（小按钮）
        JButton generateBtn = new JButton("执行");
        generateBtn.setPreferredSize(new Dimension(100, 30));
        generateBtn.setAlignmentX(Component.LEFT_ALIGNMENT);
        setupAction(generateBtn, fields);
        inputPanel.add(generateBtn);

        // 返回结果字段（统一显示SQL或JSON）
        JPanel resultPanel = new JPanel(new BorderLayout());
        resultPanel.setBorder(BorderFactory.createTitledBorder("返回结果"));
        JScrollPane resultScrollPane = new JScrollPane(fields.resultSqlArea);
        resultScrollPane.setPreferredSize(new Dimension(0, 150));
        resultPanel.add(resultScrollPane, BorderLayout.CENTER);
        resultPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
        inputPanel.add(resultPanel);
        
        // 返回变量code字段
        JPanel resultPointCodePanel = new JPanel(new BorderLayout());
        resultPointCodePanel.setBorder(BorderFactory.createTitledBorder("返回变量code"));
        JScrollPane resultPointCodeScrollPane = new JScrollPane(fields.resultPointCodeArea);
        resultPointCodeScrollPane.setPreferredSize(new Dimension(0, 80));
        resultPointCodePanel.add(resultPointCodeScrollPane, BorderLayout.CENTER);
        resultPointCodePanel.setAlignmentX(Component.LEFT_ALIGNMENT);
        inputPanel.add(resultPointCodePanel);

        return inputPanel;
    }

    private JPanel createFormRow(String labelText, JComponent component) {
        JPanel row = new JPanel(new BorderLayout(8, 0));
        row.setAlignmentX(Component.LEFT_ALIGNMENT);

        JLabel label = new JLabel(labelText);
        label.setPreferredSize(new Dimension(LABEL_WIDTH, 26));
        row.add(label, BorderLayout.WEST);
        row.add(component, BorderLayout.CENTER);

        return row;
    }

    private JPanel createInlineFormItem(String labelText, JComponent component) {
        JPanel container = new JPanel(new BorderLayout(6, 0));
        int labelWidth = 80;
        JLabel label = new JLabel(labelText);
        label.setPreferredSize(new Dimension(labelWidth, 26));
        container.add(label, BorderLayout.WEST);
        container.add(component, BorderLayout.CENTER);

        Dimension prefSize = new Dimension(260, 32);
        container.setPreferredSize(prefSize);
        container.setMinimumSize(new Dimension(220, 32));
        container.setMaximumSize(new Dimension(320, 32));
        return container;
    }

    /**
     * 创建点位字符串集合管理面板（数组方式添加）
     */
    private JPanel createPointCodeNamePanel(MnRawDataFormFields fields) {
        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
        panel.setAlignmentX(Component.LEFT_ALIGNMENT);

        // 标签
        JLabel label = new JLabel("点位中文名称数组（逗号分隔）:");
        label.setPreferredSize(new Dimension(LABEL_WIDTH, 26));
        
        // 输入框和添加按钮
        JPanel inputRow = new JPanel(new BorderLayout(8, 0));
        JTextField inputField = new JTextField("PH,余氯,浊度");
        inputField.setColumns(15);
        JButton addBtn = new JButton("添加点位");
        
        // 点位列表
        DefaultListModel<String> listModel = new DefaultListModel<>();
        JList<String> pointList = new JList<>(listModel);
        pointList.setVisibleRowCount(3);
        JScrollPane listScrollPane = new JScrollPane(pointList);
        listScrollPane.setPreferredSize(new Dimension(0, 60));
        
        // 添加按钮事件
        addBtn.addActionListener(e -> {
            String rawText = inputField.getText();
            if (rawText == null) {
                return;
            }
            String[] points = rawText.split("[,，]");
            boolean added = false;
            for (String point : points) {
                String trimmed = point.trim();
                if (!trimmed.isEmpty()) {
                    listModel.addElement(trimmed);
                    added = true;
                }
            }
            if (added) {
                inputField.setText("");
                updatePointCodeNameField(listModel, fields.pointCodeNameField);
            }
        });
        
        // 回车键添加
        inputField.addActionListener(e -> addBtn.doClick());
        
        // 双击删除
        pointList.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                if (evt.getClickCount() == 2) {
                    int index = pointList.locationToIndex(evt.getPoint());
                    if (index >= 0) {
                        listModel.remove(index);
                        updatePointCodeNameField(listModel, fields.pointCodeNameField);
                    }
                }
            }
        });
        
        inputRow.add(inputField, BorderLayout.CENTER);
        inputRow.add(addBtn, BorderLayout.EAST);
        
        // 组装面板
        JPanel labelRow = new JPanel(new BorderLayout(8, 0));
        labelRow.add(label, BorderLayout.WEST);
        labelRow.add(inputRow, BorderLayout.CENTER);
        
        panel.add(labelRow);
        panel.add(listScrollPane);
        
        return panel;
    }
    
    /**
     * 更新点位字符串字段（将列表转换为逗号分隔的字符串）
     */
    private void updatePointCodeNameField(DefaultListModel<String> listModel, JTextField field) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < listModel.size(); i++) {
            if (i > 0) {
                sb.append(",");
            }
            sb.append(listModel.getElementAt(i));
        }
        field.setText(sb.toString());
    }

    /**
     * 设置生成SQL事件
     */
    private void setupAction(JButton generateBtn, MnRawDataFormFields fields) {
        generateBtn.addActionListener(e -> {
            try {

                // 构建DTO
                MnRawDataVO vo = fields.buildDto();

                // 调用服务生成SQL
                MnRawDataResp resp = executeMnRawData(vo);

                // 根据模拟类型显示SQL或JSON到返回结果字段
                String resultContent = "";
                if (fields.generateJsonRadio.isSelected()) {
                    // 生成JSON模式：显示JSON
                    resultContent = resp.getResultJson() != null ? resp.getResultJson() : "";
                } else {
                    // 生成SQL或插入数据库模式：显示SQL
                    resultContent = resp.getResultSql() != null ? resp.getResultSql() : "";
                }
                fields.resultSqlArea.setText(resultContent);
                fields.resultSqlArea.setCaretPosition(0);
                fields.resultSqlArea.repaint();

                // 显示点位代码到返回变量code字段（永远显示）
                fields.resultPointCodeArea.setText(resp.getResultPointCode() != null ? resp.getResultPointCode() : "");
                fields.resultPointCodeArea.setCaretPosition(0);
                fields.resultPointCodeArea.repaint();

                // 显示日志
                String logMessage;
                if (fields.generateJsonRadio.isSelected()) {
                    logMessage = "JSON 生成完成！";
                } else if (fields.insertDbRadio.isSelected()) {
                    logMessage = "数据已插入数据库！";
                } else {
                    logMessage = "SQL 生成完成！";
                }
                SwingComponentUtil.logSuccess(fields.logArea, logMessage);
                fields.logArea.setCaretPosition(fields.logArea.getDocument().getLength());
                fields.logArea.repaint();

                // 确认保存（根据模拟类型保存不同内容）
                if (fields.generateJsonRadio.isSelected()) {
                    // 保存JSON
                    if (resp.getResultJson() != null && !resp.getResultJson().isEmpty()) {
                        SwingComponentUtil.confirmAndSave(parentFrame, resp.getResultJson(), "generated_data.json", fields.logArea);
                    }
                } else if (fields.generateSqlRadio.isSelected() || fields.insertDbRadio.isSelected()) {
                    // 保存SQL
                    if (resp.getResultSql() != null && !resp.getResultSql().isEmpty()) {
                        SwingComponentUtil.confirmAndSave(parentFrame, resp.getResultSql(), "generated_sql.sql", fields.logArea);
                    }
                }

            } catch (Exception ex) {
                SwingComponentUtil.logError(fields.logArea, "执行失败", ex);
            }
        });
    }

    /**
     * 执行SQL生成
     */
    private MnRawDataResp executeMnRawData(MnRawDataVO dto) throws Exception {
        return mnDataService.mnRawData(dto);
    }
}

